package mongo

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/cgs/app/models"
	"cgs-server/server/cgs/app/models/dto"
	v1 "cgs-server/server/cgs/app/models/v1"
	"cgs-server/server/cgs/app/store"
	"cgs-server/server/model"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
)

type worksheetShortCut struct {
	db             *helper.Mongo
	collectionName string
}

func (w *worksheetShortCut) Save(wg *models.WorksheetShortCut, user *model.User, opts v1.CreateOptions) error {
	wg.ResolveEntity(wg, user)
	_, err := w.db.InsertOne(w.collectionName, wg)
	return err
}

//func (w *worksheetShortCut) Get(wg *models.WorksheetShortCut, user *model.User, opts v1.Options) (*vo.WorksheetShortCut, error) {
//	filter := bson.M{}
//	if !wg.Id.IsZero() {
//		filter["id"] = wg.Id
//	}
//	//if wg.AppId != "" {
//	//	filter["appId"] = wg.AppId
//	//}
//	//wg.ResolveFilter(wg, user, &filter)
//	result := &vo.WorksheetShortCut{}
//
//	return result, nil
//}

func (w *worksheetShortCut) Update(wg *dto.WorksheetShortCut, user *model.User, opts v1.UpdateOptions) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	} else {
		return fmt.Errorf("id is required")
	}
	wg.ResolveFilter(wg, user, &filter)
	set := bson.M{}

	if wg.WorksheetInfoIds != nil {
		set["worksheetInfoIds"] = wg.WorksheetInfoIds
	}
	wg.ResolveUpdateCondition(wg, user, &set)
	update := bson.M{
		"$set": set,
	}
	_, err := w.db.UpdateOne(w.collectionName, filter, update)
	return err
}

func (w *worksheetShortCut) Delete(wg *models.WorksheetShortCut, user *model.User, opts bson.M) error {
	filter := bson.M{}
	if !wg.Id.IsZero() {
		filter["id"] = wg.Id
	}
	wg.ResolveFilter(wg, user, &filter)

	_, err := w.db.DeleteMany(w.collectionName, opts)
	return err
}

func (w *worksheetShortCut) List(wg *models.WorksheetShortCut, user *model.User, opts v1.ListOptions) (*[]bson.M, error) {
	filter := opts.GetFilter()
	wg.ResolveFilter(wg, user, &filter)
	shortCut := &[]bson.M{}
	err := w.db.FindMany(w.collectionName, filter, shortCut, opts.ResolveFindOptions())
	return shortCut, err
}

func newWorksheetShortCutStore(d *datastore) store.WorksheetShortCutStore {
	return &worksheetShortCut{
		db:             d.db,
		collectionName: server.WorksheetShortCutCollectionName,
	}
}
